#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
import os
import json
import urllib
import urllib2
import time
import datetime
import calendar
import math
import re
import decimal
from multiprocessing import Process
reload(sys)
sys.setdefaultencoding('utf-8')
#生成insert语句的字段及值部分
def makeSqlKeyValue(data):
    k=[]
    v=[]
    u=[]
    keys=data.keys()
    keys.sort()
    for i in keys:
        k.append('`%s`' % i)
        if data[i]=='NULL':
            temp='NULL'
        elif data[i] is None:
            temp="''"
        else:
            temp="'%s'" % data[i]
        v.append(temp)
        u.append("%s=%s" % (i,temp))
    key='(%s)' % ','.join(k)
    value='(%s)' % ','.join(v)
    update=','.join(u)
    return {'key':key,'value':value,'update':update}
#生成一条insert语句
def makeOneInsertSql(table,data):
    kv=makeSqlKeyValue(data)
    return 'insert into %s %s values %s;\n' % (table,kv['key'],kv['value'])
#生成一条insert语句(多个values)
def makeMoreInsertSql(table,data):
    kv=makeSqlKeyValue(data[0])
    values=[]
    for item in data:
        current=makeSqlKeyValue(item)
        values.append(current['value'])
    return 'insert into %s %s values %s;' % (table,kv['key'],','.join(values))
#根据日期获取时间戳
def getTimestampByDate(date):
    DATE_TIME=time.strptime(date,'%Y-%m-%d')
    return time.mktime(DATE_TIME)
#根据日期时间获取时间戳
def getTimestampByDateTime(datetime):
    DATE_TIME=time.strptime(datetime,'%Y-%m-%d %H:%M:%S')
    return time.mktime(DATE_TIME)
#根据时间戳获取日期
def getDateByTimestamp(timestamp):
    DATE_TIME=time.localtime(timestamp)
    return time.strftime('%Y-%m-%d',DATE_TIME)
#根据时间戳获取日期时间
def getDateTimeByTimestamp(timestamp):
    DATE_TIME=time.localtime(timestamp)
    return time.strftime('%Y-%m-%d %H:%M:%S',DATE_TIME)
#日期偏移
def getOffsetDate(date,offset_day):
    second=getTimestampByDate(date)
    second+=86400*offset_day
    return getDateByTimestamp(second)
#是否每月第1天
def isMonthFirst(date):
    return date[8:10]=='01'
#获取当前日期时间
def getDateTime(offset_day=0):
    timestamp=time.time()
    if offset_day!=0:
        timestamp+=offset_day*86400
    DATE_TIME=time.localtime(timestamp)
    return time.strftime('%Y-%m-%d %H:%M:%S',DATE_TIME)
#获取当前时间的整数形式
def getTimeInt():
    timestamp=time.time()
    DATE_TIME=time.localtime(timestamp)
    return time.strftime('%H%M%S',DATE_TIME)
#获取当前日期
def getDate(offset_day=0):
    timestamp=time.time()
    if offset_day!=0:
        timestamp+=offset_day*86400
    DATE_TIME=time.localtime(timestamp)
    return time.strftime('%Y-%m-%d',DATE_TIME)
#根据日期获取年月日
def getYmdByDate(date):
    timestamp=getTimestampByDate(date)
    DATE_TIME=time.localtime(timestamp)
    result={}
    result['year']=time.strftime('%Y',DATE_TIME)
    result['month']=time.strftime('%m',DATE_TIME)
    result['day']=time.strftime('%d',DATE_TIME)
    return result
#日期月范围
def getRangeDate(date):
    ymd=getYmdByDate(date)
    y=int(ymd['year'])
    m=int(ymd['month'])
    d=int(ymd['day'])
    last=calendar.monthrange(y,m)[1]
    last=str(last)
    result={}
    timestamp=getTimestampByDate(date)
    DATE_TIME=time.localtime(timestamp)
    result['first']=time.strftime('%Y-%m-01',DATE_TIME)
    temp=time.strftime('%Y-%m-last',DATE_TIME)
    temp=temp.replace('last',last)
    result['last']=temp
    result['current']=date
    return  result
#读取文件内容
def fileGetContents(name):
    result=''
    fp=open(name)
    try:
         result=fp.read()
    finally:
         fp.close()
    return result
#写入文件内容
def filePutContents(file,content):
    fp=open(file,'a')
    fp.write(content)
    fp.close()
#记录日志(相对路径)
def log(file,content):
    path='%s/%s' % (os.getcwd(),file)
    content="%s->%s\n" % (getDateTime(),content)
    filePutContents(path,content)
#递归删除目录下文件
def emptyDir(path):
     for file in os.listdir(path):
         target=os.path.join(path,file)
         if os.path.isfile(target):
             os.remove(target)
#大数据分批处理
def idBetween(minId,maxId,span=500000):
    array=[]
    start=minId
    end=0
    while end<maxId:
        end=start+span
        if end>maxId:
            end=maxId
        array.append({'start':start,'end':end})
        start=end+1
    return array
#删除一个表重复的数据的sql
def deleteTableRepeatDataSql(table,field):
    return "delete a.* from %s as a left join (select id from %s group by %s) as b on a.id=b.id where b.id is null" % (table,table,field)
#ifnone
def ifNone(variable,default=''):
    if variable is None:
        return default
    else:
        return variable
#if
def ifif(v,v1,v2):
    if v:
        return v1
    else:
        return v2
#根据日期范围生成列表
def getDateList(start_date,end_date):
    result=[]
    second=86400
    start_date_second=int(getTimestampByDate(start_date))
    end_date_second=int(getTimestampByDate(end_date))
    span=(end_date_second-start_date_second)/second+1
    for i in range(span):
        temp=start_date_second+i*second
        result.append(getDateByTimestamp(temp))
    return result
#尝试取一个值
def getSet(data,key):
    if key in data:
        return data[key]
    else:
        return 0
def makeDeleteSqlByPage(table,field,minId,maxId,span):
    sqls=[]
    start=minId
    end=0
    while end<maxId:
        end=start+span
        if end>maxId:
            end=maxId
        sqls.append("delete from %s where %s between %s and %s" % (table,field,start,end))
        start=end+1
    return sqls
